<?php
class NestedMessage extends MessageBaseControl
{
    public static $message;
	public $header;
	public $isPassed;
	public $error = array();
	public static $message = array();
	protected static $messageStack = array();
	public $passedCount;
	public $failedCount;

	public function NestedMessage($header = null)
	{
		$this->header = $header;
	}

	public static function Flash()
	{
		$flashes = array();
        foreach (self::$message as $msg)
		{
			$flashes[] = $msg->Render();
		}
		self::$message = array();
		return $flashes;
	}

	public static function Add($message)
	{
		if (empty(self::$messageStack))
			self::$message[] = $message;
		else
		{
			$count = count(self::$messageStack);
			$parent_msg = self::$messageStack[$count-1];
			$parent_msg->AddChild($message);
		}
	}

	public static function Push($message)
	{
		self::Add($message);
		array_push(self::$messageStack, $message);
	}

	public static function Pop()
	{
		array_pop(self::$messageStack);
	}

    public function Render()
    {
		$header = $this->header ? "<b>$this->header</b> -" : null;
    	if ($this->isPassed)
    	{
    		$this->status = 'confirm';
    		$passed = '<b>Passed</b>';
		}
    	else
    	{
    		$this->status = 'warning';
    		$passed = '<b>Failed</b>';
		}

		$log = null;
        foreach ($this->error as $key => $value)
		{
			$css = $value['is_passed'] ? 'passed':'failed';
			$log .= "<tr class='$css'>
						<td>$key</td>
						<td>{$value['expected']}</td>
						<td>{$value['supplied']}</td></tr>";
		}

		$this->content = "<table class='testlog'>
							<thead>
								<th>key</th>
								<th>expected</th>
								<th>supplied</th>
							</thead>
							<tbody>$log</tbody>
						</table>";
		$this->content .= $this->RenderChilds();
		$flash['status'] = $this->status;
		$flash['msg'] = $this->content;
		$flash['header'] = "$header $passed";
		return $flash;
    }

    public function IsPassed()
    {
    	$this->passedCount = 0;
    	$this->failedCount = 0;
    	if (!empty($this->childs))
    	{
    		$this->isPassed = true;
    		foreach ($this->childs as $child)
    		{
    			$childPassed = method_exists($child, 'IsPassed')? $child->IsPassed() : true;
    			$this->isPassed &= $childPassed;

				if ($childPassed) $this->passedCount++;
				else $this->failedCount++;
    		}
		}
		return $this->isPassed;
    }
}
?>
